package com.bosssoft.base.entity;

import com.bosssoft.base.enums.ResultCodeEnum;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 统一返回结果集
 *
 * @author diana
 * @create 2021-03-31 10:59
 */
@Data
@ApiModel("全局统一返回结果")
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {

    /**
     * 返回码
     */
    @ApiModelProperty(value = "返回码")
    private Integer code;

    /**
     * 返回消息
     */
    @ApiModelProperty(value = "返回消息")
    private String message;

    /**
     * 返回数据
     */
    @ApiModelProperty(value = "返回数据")
    private T data;

    protected static <T> Result<T> build(T data) {
        Result<T> result = new Result<>();
        if (data != null) {
            result.setData(data);
        }
        return result;
    }

    public static <T> Result<T> build(Integer code, String message, T data) {
        Result<T> result = build(data);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    public static <T> Result<T> build(T data, ResultCodeEnum resultCodeEnum) {
        Result<T> result = build(data);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }

    /**
     * 操作成功
     *
     * @param data 数据
     * @param <T>  泛型
     * @return 统一结果
     */
    public static <T> Result<T> ok(T data) {
        return build(data, ResultCodeEnum.SUCCESS);
    }

    public static <T> Result<T> ok(String message) {
        return build(ResultCodeEnum.SUCCESS.getCode(), message, null);
    }

    public static <T> Result<T> ok() {
        return Result.ok(null);
    }

    /**
     * 操作失败
     *
     * @param data 数据
     * @param <T>  泛型
     * @return 统一结果
     */
    public static <T> Result<T> error(T data) {
        return build(data, ResultCodeEnum.ERROR);
    }

    public static <T> Result<T> error(String message) {
        return build(ResultCodeEnum.ERROR.getCode(), message, null);
    }

    public static <T> Result<T> error() {
        return Result.error(null);
    }

    public Result<T> message(String msg) {
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code) {
        this.setCode(code);
        return this;
    }

    public Result<T> data(T data) {
        this.setData(data);
        return this;
    }

    public boolean isOk() {
        return this.getCode().intValue() == ResultCodeEnum.SUCCESS.getCode().intValue();
    }
}
